package com.resou.reader.mine.model;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.RequestOptions;
import com.resou.reader.R;
import com.resou.reader.bookshelf.listener.OnItemClickListener;

import java.io.File;
import java.util.List;

/**
 * Created by ${Garrett} on 2018/8/31.
 * Contact me krouky@outlook.com
 */
public class LocalImageAdapter extends RecyclerView.Adapter<LocalImageAdapter.ViewHolder> {
    private static final int TYPE_CAMERA = 1;
    private static final int TYPE_PHOTO = 2;

    private List<String> mList;
    private OnItemClickListener mListener;

    public LocalImageAdapter(List<String> list, OnItemClickListener listener) {
        mList = list;
        mListener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new ViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.choise_photo_item, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
        String filePath = mList.get(i);
        if (getItemViewType(i) == TYPE_CAMERA) {
            viewHolder.iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            viewHolder.iv.setImageResource(R.mipmap.ic_camera);
        } else {
            viewHolder.iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            RequestOptions options = new RequestOptions();
            options.format(DecodeFormat.PREFER_RGB_565);
            Glide.with(viewHolder.itemView).load(new File(filePath)).apply(options).into(viewHolder.iv);
        }
    }

    @Override
    public int getItemCount() {
        return mList == null ? 1 : mList.size();
    }

    @Override
    public int getItemViewType(int position) {
        return position == 0 ? TYPE_CAMERA : TYPE_PHOTO;
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        ImageView iv;

        ViewHolder(@NonNull final View itemView) {
            super(itemView);
            iv = itemView.findViewById(R.id.choice_photo_iv);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        mListener.onItemClicked(LocalImageAdapter.this, itemView, getAdapterPosition());
                    }
                }
            });
        }
    }
}
